package com.zb.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zb.common.exception.BusinessException;
import com.zb.common.mapper.Role2MenuMapper;
import com.zb.common.mapper.RoleMapper;
import com.zb.common.mapper.UserMapper;
import com.zb.common.po.enums.PageSize;
import com.zb.common.po.enums.RoleStatus;
import com.zb.common.po.model.Menu;
import com.zb.common.po.model.Role;
import com.zb.common.po.model.Role2Menu;
import com.zb.common.po.query.RoleQuery;
import com.zb.common.utils.PaginationResult;
import com.zb.common.utils.SimplePage;
import com.zb.service.RoleService;

@Service(value = "roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private Role2MenuMapper role2MenuMapper;

    @Resource
    private RoleMapper roleDao;

    @Resource
    private UserMapper userDao;

    private static final Logger logger = LoggerFactory
            .getLogger(RoleServiceImpl.class);

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveRole(Role role, Integer[] menuIds) throws BusinessException {
        try {
            if (null == role || StringUtils.isEmpty(role.getRoleName())) {
                throw new BusinessException("参数错误");
            }
            if (null == menuIds || menuIds.length == 0) {
                throw new BusinessException("请选择菜单");
            }
            // 先插入，或者更新数据
            if (null == role.getId()) {
                role.setCreateTime(new Date());
                roleDao.insertRole(role);
            } else {
                roleDao.updateRoleSelective(role);
            }
            // 再判断是否有重名的角色
            RoleQuery query = new RoleQuery();
            query.setRoleName(role.getRoleName());
            query.setStatus(RoleStatus.NORMAL);
            List<Role> roleList = roleDao.selectRoles(query);
            // 判断角色重名
            if (roleList.size() > 1) {
                throw new BusinessException("角色名称已经存在！");
            }
            // 删除角色下的菜单
            role2MenuMapper.deleteByRoleId(role.getId());
            List<Role2Menu> list = new ArrayList<Role2Menu>();
            for (Integer menuId : menuIds) {
                Role2Menu role2Menu = new Role2Menu();
                role2Menu.setRoleId(role.getId());
                role2Menu.setMenuId(menuId);
                list.add(role2Menu);
            }
            if (!list.isEmpty()) {
                role2MenuMapper.insertRole2MenuBatch(list);
            }
        } catch (BusinessException e) {
            throw new BusinessException(e.getMessage());
        } catch (Exception e) {
            logger.info("[比特球运维管理后台]保存角色异常：{}", e);
            throw new BusinessException("保存角色异常");
        }

    }

    @Override
    public List<Menu> findRole2MenuByRoleId(Integer roleId) {
        List<Menu> list = this.role2MenuMapper.selectRole2MenuByRoleId(roleId);
        return list;
    }

    private List<Role2Menu> getChildMenue(List<Role2Menu> list, int pid) {
        List<Role2Menu> resultList = new ArrayList<Role2Menu>();
        Iterator<Role2Menu> iterator = list.iterator();
        while (iterator.hasNext()) {
            Role2Menu subMenu = iterator.next();
            if (pid == subMenu.getpMenuId().intValue()) {
                subMenu.setChildMenu(getChildMenue(list, subMenu.getMenuId()));
                resultList.add(subMenu);
            }
        }
        return resultList;
    }

    @Override
    public Role getRoleById(Integer roleId) throws BusinessException {
        RoleQuery query = new RoleQuery();
        query.setRoleId(roleId);
        List<Role> roleList = roleDao.selectRoles(query);
        if (roleList.size() != 1) {
            throw new BusinessException("角色数据异常");
        }
        return roleList.get(0);
    }

    @Override
    public PaginationResult<Role> findRolesbyPage(RoleQuery query) {
        int count = this.roleDao.selectRoleCount(query);
        int pageSize = PageSize.SIZE20.getSize();
        int pageNo = 0;
        if (null != query.getPageNo()) {
            pageNo = query.getPageNo();
        }
        SimplePage page = new SimplePage(pageNo, count, pageSize);
        query.setPage(page);
        List<Role> list = this.roleDao.selectRoles(query);
        PaginationResult<Role> result = new PaginationResult<Role>(page, list);
        return result;
    }

    @Override
    public List<Role> findAllRoles(RoleQuery query) {
        List<Role> list = this.roleDao.selectRoles(query);
        return list;
    }

    @Override
    public void deleteRoleBatch(String[] idsArray) throws BusinessException {
        if (null == idsArray || idsArray.length == 0) {
            throw new BusinessException("参数错误");
        }

        List<String> idList = Arrays.asList(idsArray);
        // 查询角色是否被用户使用
        int count = this.userDao.selectUserCountUseRoles(idList);
        if (count > 0) {
            throw new BusinessException("角色正在被使用，不能删除");
        }
        this.roleDao.updateRoleStatusByIds(RoleStatus.DELETE, idList);
    }
}
